/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdlib.h>
#include <string.h>
#include <seos.h>
#include <timer.h>


/* Private driver events */
enum testEvents {
    EVT_TEST_EVENT = EVT_APP_START + 1,
    EVT_TEST_TIMER,
};

static struct testTask {
    uint32_t test_global;
    uint32_t taskId;
    uint32_t timerHandle;
    uint32_t debugCount;
} mTask;
#if 1
static void testTimerCallback(uint32_t timerId, void *cookie)
{
    mTask.debugCount++;

    //osLog(LOG_INFO, "[test] testTimerCallback:%lld\n", timGetTime());
    if (!osEnqueuePrivateEvt(EVT_TEST_TIMER, NULL, NULL, mTask.taskId))
        osLog(LOG_INFO, "[test] enqueue EVT_TEST_TIMER fail\n");
}
#endif
static void testHandleEvent(uint32_t evtType, const void* evtData)
{
    static uint32_t event_number = 0;
    static uint64_t last_time = 0;
    uint64_t now_time = 0;

    switch (evtType) {
        case EVT_APP_START:
            osLog(LOG_INFO, "[test] idle\n");
            last_time = timGetTime();
            osEventUnsubscribe(mTask.taskId, EVT_APP_START);
            mTask.timerHandle = timTimerSet(500000000, 0, 50, testTimerCallback, NULL, false /* periodic */);

            if (!osEnqueuePrivateEvt(EVT_TEST_EVENT, NULL, NULL, mTask.taskId))
                osLog(LOG_INFO, "[test] enqueue EVT_TEST_EVENT fail\n");

            break;

        case EVT_TEST_EVENT:
            now_time = timGetTime();

            if (now_time - last_time >= 2000000000) {
                event_number++;
                osLog(LOG_INFO, "[test] EVT_TEST_EVENT, system time:%lld\n", now_time);
                last_time = now_time;
            }

            if (!osEnqueuePrivateEvt(EVT_TEST_EVENT, NULL, NULL, mTask.taskId))
                osLog(LOG_INFO, "[test] enqueue EVT_TEST_EVENT fail\n");

            break;

        case EVT_TEST_TIMER:
            osLog(LOG_INFO, "[test] EVT_TEST_TIMER, system time:%lld, event_number:%d, debugCount:%d\n",
                  timGetTime(), event_number, mTask.debugCount);
            break;
    }
}

static bool testStart(uint32_t taskId)
{
    osLog(LOG_INFO, "[test] test_global:%d, taskId:%d\n", mTask.test_global, taskId);
    mTask.taskId = taskId;
    osEventSubscribe(taskId, EVT_APP_START);
    return true;
}

static void testEnd()
{
}

INTERNAL_APP_INIT(
    APP_ID_MAKE(APP_ID_VENDOR_GOOGLE, 8),
    0,
    testStart,
    testEnd,
    testHandleEvent);

